<?php
namespace app\api\controller;

use app\api\job\GameNotifyJob;
use app\common\controller\WeiXinpay;
use think\Controller;
use think\facade\Log;
use app\common\model\Order;
use app\common\model\Gameplog;
use app\common\model\OrderLog;
use think\Db;
use think\facade\Request;
use think\Queue;
use app\common\model\Channel;
use app\common\model\Gamelist;

/**
 * 渠道支付回调接口，通知到游戏
 */
class ChannelGameNotify extends Controller
{

    /**
     * 渠道支付回调接口
     * 接收渠道数据，返回成功
     * @return string
     */
    public function notify(){
        // 获取通知参数
        $params = $this->request->param();

        // 记录通知日志
        Log::info('渠道支付通知参数：' . json_encode($params));
        file_put_contents(__DIR__.'/channel_pay_notify.txt', json_encode($params) . "\n");
         // 校验数据
        if(empty($params['cid']) || !isset($params['cid'])){
            log::info('渠道参数错误：');
            echo "渠道id错误";exit;
        }
        // 游戏参数
        $gid = $params['gid'];
        unset($params['gid']);

        $game = Gamelist::find($gid);

        if(empty($game) || $game['gstatus'] == 0){
            echo "游戏数据错误";exit;
        }
        $cid = $params['cid'];
        unset($params['cid']);
        // 校验渠道
        $channel = Channel::getUserById($cid);
        if(empty($channel) || $channel['status'] !=1){
            echo "渠道错误";exit;
        }
        // 检验签名 初始化对控制器，调用签名验证方法，默认调用公共方法
        $channelName = ucfirst($channel['username']);
        // 动态加载自定义类（例如：app\common\CustomClass
        $className ='app\faxing\channel\\'.$channelName; // 替换为你的类名
        if (!class_exists($className)) {
            Log::info("渠道类初始化失败");
        }
        //订单校验
        $gameapi = new $className();
        $order = $gameapi->check_order($params);

        if($order === false){
            Log::info("订单数据错误。");exit;
        }
        // 返回状态
        $gameapi->message($this->orderHandle($order),$order);
    }

    /**
     * 支付成功订单处理
     */
    private function orderHandle($order) {
        if(in_array($order['order_status'],[1,2,3,4])){
            return 'success';
        }
        Db::startTrans();
        try {
            // 更新订单状态
            $order->order_status = 1; // 支付成功
            $order->pay_time = date('Y-m-d H:i:s');
            $order->update_time = date('Y-m-d H:i:s');
            $order->save();

            // 记录游戏充值日志
            Gameplog::addLog([
                'uid' => $order['uid'],
                'cid' => $order['cid'],
                'gid' => $order['gid'],
                'sid' => $order['sid'],
                'order_no' => $order['order_no'],
                'order_status' => $order['order_status'],
                'amount' => $order['amount'],
                'type' => $order['type'], // 支付宝支付
                'status' => 1, // 成功
                'create_time' => date('Y-m-d H:i:s'),
                'pay_time' =>$order['pay_time'],
                'pay_status' => 1
            ]);
            OrderLog::addLog($order->order_no, $order->order_status, $order->type);
            Db::commit();

            //添加redis队列、通知到游戏
            Queue::push(GameNotifyJob::class, ['order_no' => $order['order_no']]);
            return 'success';
        } catch (\Exception  $e) {
            Log::error('订单处理异常：' . $e->getMessage());
            Db::rollback();
        }
    }

}
